package com.hepinghospital.user.ui.activity.nursing;

import android.Manifest;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hepinghospital.user.R;
import com.hepinghospital.user.adapter.MedicineChatAdapter;
import com.hepinghospital.user.base.BaseActivity;
import com.hepinghospital.user.base.BaseApplication;
import com.hepinghospital.user.eventbus.WebSocket;
import com.hepinghospital.user.eventbus.WebSocketWrapper;
import com.hepinghospital.user.ui.activity.consult.ChatActivity;
import com.hepinghospital.user.ui.activity.consult.PhoneActivity;
import com.hepinghospital.user.ui.activity.eyecheck.BigImageActivity;
import com.hepinghospital.user.ui.activity.home.AddRegistrationActivity;
import com.hepinghospital.user.ui.activity.nursing.interfaceUtil.FinishActivityInterface;
import com.hepinghospital.user.ui.activity.prescription.AtyOrderMedicineDetailActivity;
import com.hepinghospital.user.ui.activity.prescription.MedicineDetailActivity;
import com.hepinghospital.user.ui.dialog.ApplyPermissionDialog;
import com.hepinghospital.user.ui.dialog.ChooseDialog;
import com.hepinghospital.user.ui.dialog.SelectPicModeDialog;
import com.hepinghospital.user.ui.widget.AudioRecorderButton;
import com.hepinghospital.user.util.ImageLoaderHelper;
import com.hepinghospital.user.util.PermissionsChecker;
import com.hepinghospital.user.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.constant.JDConstant;
import com.rest.observer.BaseObserver;
import com.rest.response.ChatResponse;
import com.rest.response.CloudResponse;
import com.rest.response.IMListResponse;
import com.rest.response.Photo;
import com.rest.response.PicUploadResponse;
import com.rest.response.Prescription2Response;
import com.rest.response.RegistrationDetailResponse;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.DpUtil;
import jz.joyoung.robot.util.LogUtil;
import jz.joyoung.robot.util.PreferencesHelper;
import jz.joyoung.robot.util.SoftKeyboardUtil;
import jz.joyoung.robot.util.TimeUtil;
import jz.joyoung.robot.util.UIConstants;
import jz.joyoung.robot.util.UriUtils;
import jz.joyoung.robot.util.UtilString;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * @Description
 * @Author WuJianFeng
 * @Date 2022/8/10 17:05
 */
@Deprecated
public class NurseConsultChatActivity extends BaseActivity implements FinishActivityInterface {

    @BindView(R.id.chat_recyclerView)
    RecyclerView chat_recyclerView;
    @BindView(R.id.photo_recyclerView)
    RecyclerView photo_recyclerView;
    @BindView(R.id.btn_context)
    TextView btn_context;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_oneselfState)
    TextView tv_oneselfState;
    @BindView(R.id.tv_patient_detail)
    TextView tv_patient_detail;
    @BindView(R.id.btn_show)
    CheckBox btn_show;
    @BindView(R.id.top)
    LinearLayout top;
    @BindView(R.id.edt_context)
    EditText edt_context;
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;
    @BindView(R.id.tv_pass)
    TextView tv_pass;
    @BindView(R.id.tv_allergy)
    TextView tv_allergy;
    @BindView(R.id.tv_close)
    TextView tv_close;
    @BindView(R.id.tv_wait)
    LinearLayout tv_wait;
    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.tv_remain_time)
    TextView tv_remain_time;
    @BindView(R.id.remain_time_container)
    ConstraintLayout remain_time_container;
    @BindView(R.id.pass_container)
    LinearLayout pass_container;
    @BindView(R.id.allergy_container)
    LinearLayout allergy_container;
    @BindView(R.id.btn_yuyin)
    AudioRecorderButton btnYuyin;
    @BindView(R.id.btn_add_photo)
    ImageView btnAddPhoto;
    @BindView(R.id.cl_bottom)
    ConstraintLayout clBottom;
    @BindView(R.id.nested_scrollView)
    NestedScrollView nestedScrollView;

    public static final int REQUEST_RECIVE_CALL = 0x033;
    public static final int REQUEST_MEDICINE = 0x044;

    PhotoAdapter adapter;
    ChatAdapter chatAdapter;
    IMListResponse.IMItem imItem;
    WebSocketWrapper ws;
    CloudResponse cloud;
    List<Photo> photoList = new ArrayList<>();
    List<ChatResponse.Message> messageList = new ArrayList<>();

    String doctorUserId, doctorId, diagnoseId, patientAvatar, doctorPicture, createTime, acceptTime, conferenceID, resourceId;
    int diagType, chatFlag;
    MediaPlayer mediaPlayer;
    private CountDownTimer timer;

    private SelectPicModeDialog mSelectPicModeDialog = null;
    // 所需的全部权限
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE
    };
    static final String[] VOICEPERMISSIONS = new String[]{
            Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private PermissionsChecker mPermissionsChecker; // 权限检测器

    private Handler mHandler = new Handler();
    //原图像 URI
    public Uri imgUriOri;
    //原图像 路径
    public static String imgPathOri;

    public ProgressDialog dialog;

    private boolean isResumed = false;

    private boolean isMeeting = false, isLoginHuaWei = false;


    private String token;

    int current = 1;
    private String patientSex;
    private String regServerAddress;
    private String serverPort;

    public static FinishActivityInterface finishActivityInterface;


    @Override
    protected void initViews() {
        GridLayoutManager manager = new GridLayoutManager(this,4);
        photo_recyclerView.setLayoutManager(manager);
        adapter = new PhotoAdapter();
        photo_recyclerView.setAdapter(adapter);
        finishActivityInterface = this;
        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, true);
//        mLayoutManager.setStackFromEnd(true);
        chatAdapter = new ChatAdapter();
        chat_recyclerView.setAdapter(chatAdapter);
//        chat_recyclerView.setHasFixedSize(true);
//        mLayoutManager.scrollToPositionWithOffset(chatAdapter.getItemCount() - 1, Integer.MIN_VALUE);
        chat_recyclerView.setLayoutManager(mLayoutManager);

        btn_show.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                btn_show.setText("展开");
                pass_container.setVisibility(View.GONE);
                allergy_container.setVisibility(View.GONE);
            } else {
                btn_show.setText("收起");
                pass_container.setVisibility(View.VISIBLE);
                allergy_container.setVisibility(View.VISIBLE);
            }
        });
        refreshLayout.setEnableLoadMore(false);
        refreshLayout.setOnRefreshListener(refreshLayout -> {
            current = 1;
            messageList.clear();
            getMessageList(diagnoseId);
        });

        btnYuyin.setAudioFinishRecorderListener((seconds, filePath) -> uploadVideo(filePath, (int) seconds));

        edt_context.setOnClickListener(v -> new Handler().postDelayed(() -> {
            chat_recyclerView.scrollToPosition(0);
            nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
            edt_context.setFocusable(true);
            edt_context.setFocusableInTouchMode(true);
            edt_context.requestFocus();
        }, 500));

        edt_context.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {

                new Handler().postDelayed(() -> {
                    chat_recyclerView.scrollToPosition(0);
                    nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
                    edt_context.setFocusable(true);
                    edt_context.setFocusableInTouchMode(true);
                    edt_context.requestFocus();
                }, 500);
            }
        });
        mPermissionsChecker = new PermissionsChecker(mContext);

    }


    @Override
    protected void initData() {
        imItem = (IMListResponse.IMItem) getIntent().getSerializableExtra("obj");
        diagnoseId = getIntent().getStringExtra("diagnoseId");
        cloud = (CloudResponse) getIntent().getSerializableExtra("cobj");
        ws = (WebSocketWrapper) getIntent().getSerializableExtra("wsObj");
        if (ws != null) {
            //移动视频的在线消息
            diagnoseId = ws.diagnoseId;
            if (ws.meetingType == 0) {
                //是移动端拉起视频
                conferenceID = ws.conferenceNum;
            } else {
                //pc端的高清会议
                conferenceID = ws.conferenceID;
            }
            getNurseConsultDetail(ws.diagnoseId);

        } else if (imItem != null) {
            diagnoseId = imItem.diagnoseId;
//            getMessageList(imItem.diagnoseId);
            getNurseConsultDetail(imItem.diagnoseId);
        } else if (cloud != null) {
            diagnoseId = cloud.diagnoseId;
//            getMessageList(cloud.diagnoseId);
            getNurseConsultDetail(cloud.diagnoseId);

        } else if (!UtilString.isEmpty(diagnoseId)) {
//            getMessageList(diagnoseId);
            getNurseConsultDetail(diagnoseId);
        }
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }


    @Override
    protected int getLayoutResource() {
        return R.layout.activity_nurse_consult_chat;
    }


    @OnClick({R.id.yuyin, R.id.btn_add_photo, R.id.cl_bottom, R.id.btn_context})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.yuyin:
                checkServiceRunning(mContext);
                // 缺少权限时, 进入权限配置页面
                if (mPermissionsChecker.lacksPermissions(VOICEPERMISSIONS)) {
                    checkVoicePermission();
                } else {
                    if (btnYuyin.getVisibility() == View.GONE) {
                        btnYuyin.setVisibility(View.VISIBLE);
                        edt_context.setVisibility(View.GONE);
                        SoftKeyboardUtil.hideSoftKeyboard(mContext);
                    } else {
                        btnYuyin.setVisibility(View.GONE);
                        edt_context.setVisibility(View.VISIBLE);
                    }
                }

                break;
            case R.id.btn_add_photo:
                checkServiceRunning(mContext);
                // 缺少权限时, 进入权限配置页面
                if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                    getPermission();
                } else {
                    showSelectHeadPicDialog();
                }
                break;
            case R.id.cl_bottom:
                new Handler().postDelayed(() -> chat_recyclerView.scrollToPosition(messageList.size() - 1), 1500);
                break;
            case R.id.btn_context:
                checkServiceRunning(mContext);
                if (TextUtils.isEmpty(edt_context.getText().toString().trim())) {
                    ToastUtil.showToast(mContext, "不能发送空白消息");
                    return;
                }
                @SuppressLint("SimpleDateFormat") SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                String clientId = TimeUtil.getClientId();
                ChatResponse.Message myMessage = new ChatResponse().new Message();
                myMessage.fromType = 0;
                myMessage.content = edt_context.getText().toString();
                myMessage.sendTime = df.format(new Date());
                myMessage.messageId = clientId;
                myMessage.flag = 1;
                messageList.add(0, myMessage);
                chatAdapter.notifyItemInserted(0);
                new Handler().postDelayed(() -> {
                    chat_recyclerView.scrollToPosition(0);
                    nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部

                }, 500);
                WebSocket webSocket = new WebSocket.Builder().content(edt_context.getText().toString()).docId(doctorId).diagnoseId(diagnoseId).from(BaseApplication.currentUserId).to(doctorUserId).msgType(0).eventFlag(1).clientId(clientId).build();
                EventBus.getDefault().postSticky(webSocket);
                edt_context.setText("");
                break;
            default:
                break;
        }
    }


    private void getNurseConsultDetail(String diagnoseId) {
        RestProxy.getInstance().getNurseConsultDetail(diagnoseId, new BaseObserver<RegistrationDetailResponse>() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(RegistrationDetailResponse registrationDetailResponse) {
                createTime = registrationDetailResponse.createTime;
                acceptTime = registrationDetailResponse.acceptTime;
                diagType = registrationDetailResponse.diagType;
                chatFlag = registrationDetailResponse.flag;
                patientSex = registrationDetailResponse.patientSex;
                tv_time.setText(createTime);
                startCountDownTimer(registrationDetailResponse.remainingTime);
                tv_title.setText(registrationDetailResponse.doctorName);
                doctorUserId = registrationDetailResponse.doctorUserId;
                doctorId = registrationDetailResponse.doctorId;
                if (registrationDetailResponse.resultList != null) {
                    if (registrationDetailResponse.resultList.size() == 0) {
                        //展示预约时上传的图片
                        photo_recyclerView.setVisibility(View.GONE);
                    }
                    photoList.clear();
                    photoList.addAll(registrationDetailResponse.resultList);
                    adapter.notifyDataSetChanged();
                }
                if (UtilString.isEmpty(registrationDetailResponse.cardType)) {
                    tv_patient_detail.setText(registrationDetailResponse.patientName + "  " + registrationDetailResponse.patientSex + "  " + registrationDetailResponse.patientAge);
                } else if ("1".equals(registrationDetailResponse.cardType)) {
                    tv_patient_detail.setText(registrationDetailResponse.patientName + "  " + registrationDetailResponse.patientSex + "  " + registrationDetailResponse.patientAge + "  自费卡");
                } else {
                    tv_patient_detail.setText(registrationDetailResponse.patientName + "  " + registrationDetailResponse.patientSex + "  " + registrationDetailResponse.patientAge + "  社保卡");
                }
//                tv_patient_detail.setText(registrationDetailResponse.data.doctorName + "  " + registrationDetailResponse.data.jobTitle + " " + (registrationDetailResponse.data.isPrescription == 0 ? "非处方" : "处方"));
                patientAvatar = registrationDetailResponse.patientAvatar;
                doctorPicture = registrationDetailResponse.doctorPicture;
//                ImageLoaderHelper.getInstance().GlideImageLoader( ChatActivity.this, registrationDetailResponse.data.doctorPicture, img_head, R.mipmap.img_default );
                tv_oneselfState.setText(registrationDetailResponse.oneselfState);
                if (TextUtils.isEmpty(registrationDetailResponse.pastHistory)) {
                    tv_pass.setText("无");
                } else {
                    tv_pass.setText(registrationDetailResponse.pastHistory);
                }
                if (TextUtils.isEmpty(registrationDetailResponse.allergyHistory)) {
                    tv_allergy.setText("无");
                } else {
                    tv_allergy.setText(registrationDetailResponse.allergyHistory);
                }
                if (registrationDetailResponse.flag == UIConstants.CHAT_STATE_2) {
                    tv_close.setVisibility(View.VISIBLE);
                    clBottom.setVisibility(View.INVISIBLE);
                    tv_wait.setVisibility(View.GONE);
                    remain_time_container.setVisibility(View.GONE);
                } else if (registrationDetailResponse.flag == UIConstants.CHAT_STATE_0) {
                    //等待
                    clBottom.setVisibility(View.INVISIBLE);
                    if (diagType == UIConstants.DIAGNOSE_TYPE_1 || diagType == UIConstants.DIAGNOSE_TYPE_4) {
                        tv_wait.setVisibility(View.VISIBLE);
                    } else {
                        tv_wait.setVisibility(View.GONE);
                    }
                    remain_time_container.setVisibility(View.GONE);
//                    tv_time.setText(registrationDetailResponse.data.);
                } else if (registrationDetailResponse.flag == UIConstants.CHAT_STATE_1) {
                    clBottom.setVisibility(View.VISIBLE);
                    tv_wait.setVisibility(View.GONE);
                    if (diagType == UIConstants.DIAGNOSE_TYPE_1 || diagType == UIConstants.DIAGNOSE_TYPE_4) {
                        remain_time_container.setVisibility(View.VISIBLE);
                    } else {
                        remain_time_container.setVisibility(View.GONE);
                    }
                }
//                boolean isShowPhone = PreferencesHelper.getInstance().getBoolean(ChatActivity.this, "isShowPhone");
//                if (!isShowPhone) {
                //   推送后，患者端加入会议
                if (ws != null) {
//                    MeetingMgr.getInstance().queryMyConfList( ConfConstant.ConfRight.MY_CREATE_AND_JOIN );
                    PreferencesHelper.getInstance().set(NurseConsultChatActivity.this, "isShowPhone", true);
                    Bundle bundle = new Bundle();
                    bundle.putString("doctor", registrationDetailResponse.doctorName + "  " + registrationDetailResponse.jobTitle);
                    bundle.putString("doctorPicture", registrationDetailResponse.doctorPicture);
                    startActivityForResult(PhoneActivity.class, bundle, REQUEST_RECIVE_CALL);
                }
//                }
                current = 1;
                messageList.clear();
                getMessageList(diagnoseId);
            }

            @Override
            public void onError(Throwable e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtil.onError(NurseConsultChatActivity.this, e);

                    }
                });
            }
        });
    }

    /**
     * 查看聊天记录
     *
     * @time 2020/12/7 10:47
     */
    private void getMessageList(String diagnoseId) {
//        current++;
        RestProxy.getInstance().getChatList(diagnoseId, current + "", new Observer<ChatResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(ChatResponse chatResponse) {
                if (chatResponse.records != null) {
                    messageList.addAll(chatResponse.records);
                    if (diagType == UIConstants.DIAGNOSE_TYPE_1 && chatFlag != UIConstants.CHAT_STATE_0) {
                        if (chatResponse.current == chatResponse.pages || chatResponse.pages == 0) {
                            if (messageList.size() > 0 && messageList.get(messageList.size() - 1).messageType == 10) {
                                return;
                            }
                            ChatResponse.Message message = new ChatResponse().new Message();
                            message.messageType = 10;
                            messageList.add(message);
                        }
                    }
                    if (diagType == UIConstants.DIAGNOSE_TYPE_1 && chatFlag == UIConstants.CHAT_STATE_2) {
                        if (messageList.size() > 0 && messageList.get(0).messageType == 11) {
                            return;
                        }
                        ChatResponse.Message message = new ChatResponse().new Message();
                        message.messageType = 11;
                        messageList.add(0, message);
                    }
                }
                chatAdapter.notifyDataSetChanged();
                if (current == 1) {
                    new Handler().postDelayed(() -> {
                        chat_recyclerView.scrollToPosition(0);
                        nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
                    }, 1000);
                }
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.onError(NurseConsultChatActivity.this, e);
                refreshLayout.finishRefresh(false);
            }

            @Override
            public void onComplete() {
                refreshLayout.finishRefresh(true);
            }
        });
    }

    private void updateDiagnoseStatus(String doctorUserId, String diagnoseId, final int status) {
        RestProxy.getInstance().updateDiagnoseStatus(doctorUserId, diagnoseId, status + "", new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(String String) {
                if (status == 1) {
                    finish();
                }
                mChooseDialog.dismiss();
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.onError(NurseConsultChatActivity.this, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }


    private void finishMeeting() {
        RestProxy.getInstance().finishMeeting(BaseApplication.currentUserId, diagnoseId, doctorUserId, conferenceID, ws.meetingType + "", new BaseObserver<String>() {
            @Override
            public void onSuccess(String result) {

            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            //data的返回值根据
            switch (requestCode) {
                case AddRegistrationActivity.REQUEST_OPEN_CAMERA:
                    getPresignedUrl(imgPathOri);
//                    uploadFile( imgPathOri );
                    break;
                case AddRegistrationActivity.REQUEST_GALLERY:
                    if (data != null) {
                        Uri imgUriSel = data.getData();
                        String imgPathSel = UriUtils.formatUri(this, imgUriSel);
//                        uploadFile( imgPathSel );
                        getPresignedUrl(imgPathSel);
                    }
                    break;
                case REQUEST_RECIVE_CALL:
                    //接受视频会议,加入会议
                    isMeeting = true;
                    break;
                case REQUEST_MEDICINE:
                    messageList.clear();
                    current = 1;
                    getMessageList(diagnoseId);
                    break;
            }
        } else if (resultCode == RESULT_CANCELED) {
            if (requestCode == REQUEST_RECIVE_CALL) {
                //拒绝会议视频
                finishMeeting();
            }
        }
    }


    private void uploadVideo(String imgPathSel, int time) {
        RestProxy.getInstance().uploadVideo(new File(imgPathSel), new Observer<PicUploadResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
//                dialog = ProgressDialog.show(ChatActivity.this, "提示", "正在上传中…", true, false, null);
            }

            @Override
            public void onNext(PicUploadResponse picUploadResponse) {
                ChatResponse.Message message = new ChatResponse().new Message();
                @SuppressLint("SimpleDateFormat") SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                message.messageType = 2;
                message.fromType = 0;
                message.content = picUploadResponse.shareUrl;
                message.src = picUploadResponse.shareUrl;
                message.sendTime = df.format(new Date());
                message.time = time;
                messageList.add(0, message);
                chatAdapter.notifyItemInserted(0);
                new Handler().postDelayed(() -> {
//                    chat_recyclerView.scrollToPosition( 0 );
                    nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部

                }, 500);
                WebSocket webSocket = new WebSocket.Builder().content(picUploadResponse.shareUrl).docId(doctorId).diagnoseId(diagnoseId).from(BaseApplication.currentUserId).to(doctorUserId).picType("wav").msgType(2).eventFlag(1).clientId(TimeUtil.getClientId()).time(time).build();
                EventBus.getDefault().postSticky(webSocket);
            }

            @Override
            public void onError(Throwable e) {
                dialog.dismiss();
                ToastUtil.onError(NurseConsultChatActivity.this, e);
            }

            @Override
            public void onComplete() {
//                dialog.dismiss();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PreferencesHelper.getInstance().set(this, "isShowPhone", false);
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }

        if (timer != null) {
            timer.cancel();
        }
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
        }

        if (finishActivityInterface != null) {
            finishActivityInterface = null;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(WebSocket webSocket) {
        if (webSocket.eventFlag == 0) {
            if (webSocket.diagnoseId.equals(diagnoseId)) {
                if (webSocket.msgType != 6) {
                    ChatResponse.Message message = new ChatResponse().new Message();
                    @SuppressLint("SimpleDateFormat") SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                    message.messageType = webSocket.msgType;
                    message.content = webSocket.content;
                    message.src = webSocket.src;
                    message.sendTime = webSocket.createTime;
                    message.time = webSocket.time;
                    message.fromType = 1;
                    messageList.add(0, message);
                    chatAdapter.notifyItemInserted(0);
                    chatAdapter.notifyDataSetChanged();
                    nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
                } else {
                    //msgType==6代表处方消息
                    if (!UtilString.isEmpty(webSocket.preId)) {
                        getPrescription(webSocket.preId);
                    }
                }
                WebSocket webSocket2 = new WebSocket();
                webSocket2.cmd = 24;
                webSocket2.diagnoseId = webSocket.diagnoseId;
                webSocket2.to = webSocket.to;
                webSocket2.msgId = webSocket.id;
                webSocket2.eventFlag = 4;
                EventBus.getDefault().postSticky(webSocket2);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent2(WebSocketWrapper webSocket) {
        if (webSocket.cmd == 100) {
            finish();
        } else if (webSocket.cmd == 108) {
//            getMessageList(diagnoseId);
            getNurseConsultDetail(diagnoseId);
        } else if (webSocket.cmd == 110 || webSocket.cmd == 112) {
            current = 1;
            messageList.clear();
            getMessageList(diagnoseId);
        } else if (webSocket.code == 10000 || webSocket.code == 10001) {
            for (int i = 0; i < messageList.size(); i++) {
                if (TextUtils.isEmpty(messageList.get(i).messageId)) {
                    return;
                }
                if (messageList.get(i).messageId.equals(webSocket.clientId)) {
                    messageList.get(i).flag = UIConstants.CHAT_STATE_0;
                    chatAdapter.notifyItemChanged(i);
//                    chat_recyclerView.scrollToPosition( 0 );
                    nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
                }
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        isResumed = true;

    }

    @Override
    protected void onNewIntent(Intent intent) {
        Log.e("onnewintent", "onnewintent");
        long userid = intent.getLongExtra("userid", 0);
//        ws = (WebSocketWrapper) intent.getSerializableExtra("wsObj");
//        if (ws != null) {
//            diagnoseId = ws.diagnoseId;
//            startActivityForResult(PhoneActivity.class, REQUEST_RECIVE_CALL);
//        }
        if (userid != 0) {
//            checkPermissionAndShow( userid );
        } else {
//            Intent intents = new Intent( ChatActivity.this, FloatingService.class );
//            stopService( intents );
        }
        super.onNewIntent(intent);
    }


    @Override
    protected void onPause() {
        super.onPause();
        isResumed = false;
    }


    @Override
    public void initBack() {
        btn_back = findViewById(R.id.btn_back);
        if (btn_back != null) {
            btn_back.setOnClickListener(v -> {
                finish();
            });
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            finish();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    private ChooseDialog mChooseDialog;

    private void getPrescription(String preId) {
        LogUtil.e("处方id----", preId + "");
        RestProxy.getInstance().getPrescription(preId, new Observer<Prescription2Response>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(Prescription2Response prescriptionResponse) {
//                current = 0;
//                messageList.clear();
//                getMessageList( diagnoseId );
//                ChatResponse.Message message = new ChatResponse().new Message();
//                message.messageType = 6;
//                message.fromType = 1;
//                message.prescription = prescriptionResponse.data;
//                messageList.add( 0, message );
//                chatAdapter.notifyItemInserted( 0 );
//                chatAdapter.notifyDataSetChanged();
//                new Handler().postDelayed( () -> {
//                    nestedScrollView.fullScroll( ScrollView.FOCUS_DOWN );//滚动到底部
//
//                }, 500 );
            }

            @Override
            public void onError(Throwable e) {
                e.printStackTrace();
                ToastUtil.onError(NurseConsultChatActivity.this, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }


    private void startLoading(View view) {
        ObjectAnimator anim = ObjectAnimator.ofFloat(view, "rotation", 0f, 360f);


        // 动画的持续时间，执行多久？
        anim.setDuration(1000);
        anim.setRepeatCount(-1);

        // 回调监听
        anim.addUpdateListener(animation -> {
            float value = (Float) animation.getAnimatedValue();
        });

        // 正式开始启动执行动画
        anim.start();
    }


    private void startCountDownTimer(String remainPayTime) {
        if (TextUtils.isEmpty(remainPayTime)) {
            return;
        }
        Log.e("倒计时===", remainPayTime);
        int parseInt = 0;
        try {
            parseInt = Integer.parseInt(remainPayTime);
        } catch (Exception e) {
            return;
        }
        timer = new CountDownTimer(parseInt, 1000) {
            @SuppressLint("SetTextI18n")
            @Override
            public void onTick(long millisUntilFinished) {
                tv_remain_time.setText(millisUntilFinished / 60000 / 60 + "时" + millisUntilFinished / 60000 % 60 + "分" + (millisUntilFinished / 1000) % 60 + "秒");
            }

            @Override
            public void onFinish() {
            }
        };
        timer.start();
    }

    class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.Holder> {

        @NotNull
        @Override
        public Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            Holder myHolder;
            myHolder = new Holder(LayoutInflater.from(NurseConsultChatActivity.this).inflate(R.layout.item_photo2, parent, false));
            return myHolder;
        }

        @Override
        public void onBindViewHolder(Holder holder, final int position) {
            holder.itemView.setOnClickListener(v -> {
                Bundle bundle = new Bundle();
                bundle.putString("url", photoList.get(position).url);
                bundle.putInt("type", 1);
                NurseConsultChatActivity.this.startActivity(BigImageActivity.class, bundle);
            });
            ImageLoaderHelper.getInstance().GlideImageLoader(NurseConsultChatActivity.this, photoList.get(position).thumbnailUrl, holder.img);
        }

        @Override
        public int getItemCount() {
            return photoList.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            ImageView img;

            public Holder(View itemView) {
                super(itemView);
                img = itemView.findViewById(R.id.image);
            }
        }
    }


    class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.Holder> {

        @NotNull
        @Override
        public Holder onCreateViewHolder(@NotNull ViewGroup parent, int viewType) {
            if (viewType == 1) {
                return new Holder(getLayoutInflater().inflate(R.layout.item_chat_left, parent, false));
            } else {
                return new Holder(getLayoutInflater().inflate(R.layout.item_chat_right, parent, false));
            }

        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(Holder holder, final int position) {
            holder.itemView.setOnClickListener(v -> {
                if (messageList.get(position).messageType == 1) {
                    Bundle bundle = new Bundle();
                    bundle.putString("url", messageList.get(position).src);
                    bundle.putInt("type", 1);
                    NurseConsultChatActivity.this.startActivity(BigImageActivity.class, bundle);
                }
            });
            if (getItemViewType(position) == 1) {
                ImageLoaderHelper.getInstance().GlideCircleImageLoader(NurseConsultChatActivity.this, doctorPicture, holder.img_head);
            } else {
                if (!UtilString.isEmpty(patientAvatar)) {
                    //加载患者头像
                    ImageLoaderHelper.getInstance().setCirclePicture(NurseConsultChatActivity.this, holder.img_head, patientAvatar);
                } else if ("女".equals(patientSex)) {
                    holder.img_head.setImageDrawable(ContextCompat.getDrawable(NurseConsultChatActivity.this, R.mipmap.icon_girl));
                } else {
                    holder.img_head.setImageDrawable(ContextCompat.getDrawable(NurseConsultChatActivity.this, R.mipmap.icon_boy));
                }
            }


            if (messageList.get(position).flag == UIConstants.CHAT_STATE_0) {
                holder.img_loading.setVisibility(View.GONE);
            } else if (messageList.get(position).flag == UIConstants.CHAT_STATE_1) {
                holder.img_loading.setVisibility(View.VISIBLE);
                startLoading(holder.img_loading);
            }

            if (messageList.get(position).messageType == 0) {
                holder.yuyin.setVisibility(View.GONE);
                holder.tv_content.setVisibility(View.VISIBLE);
                holder.img.setVisibility(View.GONE);
                holder.begin_container.setVisibility(View.GONE);
                holder.diagnose_container.setVisibility(View.GONE);
                holder.tv_content.setText(messageList.get(position).content);
                holder.tv_time.setText(messageList.get(position).sendTime);
                holder.img_head.setVisibility(View.VISIBLE);
            } else if (messageList.get(position).messageType == 1) {
                holder.yuyin.setVisibility(View.GONE);
                holder.tv_content.setVisibility(View.GONE);
                holder.img_loading.setVisibility(View.GONE);
                holder.begin_container.setVisibility(View.GONE);
                holder.img.setVisibility(View.VISIBLE);
                holder.diagnose_container.setVisibility(View.GONE);
                holder.tv_time.setText(messageList.get(position).sendTime);
                holder.img_head.setVisibility(View.VISIBLE);
                ImageLoaderHelper.getInstance().GlideImageLoader(NurseConsultChatActivity.this, messageList.get(position).content, holder.img);
            } else if (messageList.get(position).messageType == 6) {
                holder.yuyin.setVisibility(View.GONE);
                holder.tv_content.setVisibility(View.GONE);
                holder.img.setVisibility(View.GONE);
                holder.begin_container.setVisibility(View.GONE);
                holder.img_loading.setVisibility(View.GONE);
                holder.diagnose_container.setVisibility(View.VISIBLE);
                holder.img_head.setVisibility(View.GONE);
                holder.tv_time.setText(messageList.get(position).sendTime);
                if (messageList.get(position).prescription != null) {
                    holder.tv_diagnose_status.setText(messageList.get(position).prescription.pFlagStr);
                    if (messageList.get(position).prescription.orderStatus != 401) {
                        holder.btn_confirm.setVisibility(View.GONE);
                    } else if (messageList.get(position).prescription.flag == 1) {
                        holder.btn_confirm.setVisibility(View.VISIBLE);
                    }
                    if (messageList.get(position).prescription.diagnoseResult != null) {
                        holder.tv_diagnose.setText("医生意见：" + messageList.get(position).prescription.diagnoseResult);
                    } else {
                        holder.tv_diagnose.setText("医生意见：" + "无");
                    }
                    if (messageList.get(position).prescription.passTime != null) {
                        holder.tv_diagnose_time.setVisibility(View.VISIBLE);
                        holder.tv_diagnose_time.setText(messageList.get(position).prescription.passTime);
                    } else {
                        holder.tv_diagnose_time.setVisibility(View.GONE);
                    }
                    //处方药的列表
                    if (messageList.get(position).prescription.westernList != null) {
                        if (messageList.get(position).prescription.westernList.size() > 0) {
                            MedicineChatAdapter adapter;

                            adapter = new MedicineChatAdapter(NurseConsultChatActivity.this, messageList.get(position).prescription.westernList);
                            holder.recyclerView.setAdapter(adapter);
                            holder.recyclerView.setLayoutManager(new LinearLayoutManager(NurseConsultChatActivity.this));
                            holder.recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
                                @Override
                                public void onDraw(@NotNull Canvas c, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                                    super.onDraw(c, parent, state);
                                }

                                @Override
                                public void getItemOffsets(@NotNull Rect outRect, @NotNull View view, @NotNull RecyclerView parent, @NotNull RecyclerView.State state) {
                                    super.getItemOffsets(outRect, view, parent, state);
                                    outRect.bottom = DpUtil.dip2px(NurseConsultChatActivity.this, 1);
                                }
                            });
                            adapter.notifyDataSetChanged();
                        }
                    }
                    if (messageList.get(position).prescription.westernList != null) {
                        if (messageList.get(position).prescription.westernList.size() == 0) {
                            holder.tv_null.setVisibility(View.VISIBLE);
                        } else {
                            holder.tv_null.setVisibility(View.GONE);
                        }
                    } else {
                        holder.tv_null.setVisibility(View.GONE);
                    }

                    holder.btn_confirm.setOnClickListener(v -> {
                        Bundle bundle = new Bundle();
                        bundle.putString("orderId", messageList.get(holder.getAdapterPosition()).prescription.orderId);
//                        bundle.putInt("type", 3);
                        startActivityForResult(MedicineDetailActivity.class, bundle, REQUEST_MEDICINE);
                    });
                    holder.itemView.setOnClickListener(v -> {
                        Bundle bundle = new Bundle();
                        bundle.putString("orderId", messageList.get(holder.getAdapterPosition()).prescription.orderId);
                        startActivity(AtyOrderMedicineDetailActivity.class, bundle);
                    });


                }


            } else if (messageList.get(position).messageType == -1) {
                holder.yuyin.setVisibility(View.GONE);
                holder.tv_content.setText("");
            } else if (messageList.get(position).messageType == 10) {
                holder.yuyin.setVisibility(View.GONE);
                holder.img_head.setVisibility(View.GONE);
                holder.tv_content.setVisibility(View.GONE);
                holder.img_loading.setVisibility(View.GONE);
                holder.img.setVisibility(View.GONE);
                holder.diagnose_container.setVisibility(View.GONE);
                holder.begin_container.setVisibility(View.VISIBLE);
                holder.tv_time.setText(acceptTime);
                holder.textView3.setText("问诊开始");
                holder.info1.setText("1、问诊期间，您与医生对话不限次数");
                holder.info2.setText("2、问诊最长24小时，到期将自动结束");
            } else if (messageList.get(position).messageType == 11) {
                holder.yuyin.setVisibility(View.GONE);
                holder.img_head.setVisibility(View.GONE);
                holder.tv_content.setVisibility(View.GONE);
                holder.img_loading.setVisibility(View.GONE);
                holder.img.setVisibility(View.GONE);
                holder.diagnose_container.setVisibility(View.GONE);
                holder.begin_container.setVisibility(View.VISIBLE);
                holder.tv_time.setText(acceptTime);
                holder.textView3.setText("问诊结束");
                holder.info1.setText("1、问诊结论已发出，本次问诊结束");
                holder.info2.setText("2、服务评价、意见反馈请点击表扬与投诉");
            } else if (messageList.get(position).messageType == 2) {
                holder.tv_content.setVisibility(View.VISIBLE);
                holder.img.setVisibility(View.GONE);
                holder.begin_container.setVisibility(View.GONE);
                holder.diagnose_container.setVisibility(View.GONE);
                holder.tv_content.setVisibility(View.GONE);
                holder.tv_time.setText(messageList.get(position).sendTime);
                holder.img_head.setVisibility(View.VISIBLE);
                holder.yuyin.setVisibility(View.VISIBLE);
                holder.yuyin.setText(messageList.get(position).time + "''");
                if (messageList.get(position).isSpeaking) {
                    holder.yuyin.setTextColor(getResources().getColor(R.color.fff54c4c));
                } else {
                    if (getItemViewType(position) == 0) {
                        holder.yuyin.setTextColor(getResources().getColor(R.color.white));
                    } else {
                        holder.yuyin.setTextColor(getResources().getColor(R.color.mainBlue));
                    }
                }
                holder.yuyin.setOnClickListener(v -> {
                    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                        mediaPlayer.pause();
                        resetSpeakingPosition();
                    } else {
                        mediaPlayer = new MediaPlayer();
                        try {
                            mediaPlayer.setDataSource(messageList.get(holder.getAdapterPosition()).content);
                            mediaPlayer.prepareAsync(); // 准备文件
                            mediaPlayer.setOnPreparedListener(mp -> {
                                // 装载完毕回调
                                mediaPlayer.start();
                                messageList.get(holder.getAdapterPosition()).isSpeaking = true;
                                notifyItemChanged(holder.getAdapterPosition());
                            });
                            mediaPlayer.setOnCompletionListener(mp -> resetSpeakingPosition());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
            }

        }

        @Override
        public int getItemViewType(int position) {
            return messageList.get(position).fromType;
        }

        @Override
        public int getItemCount() {
            return messageList.size();
        }

        class Holder extends RecyclerView.ViewHolder {

            TextView tv_time, tv_content, btn_confirm, tv_diagnose, tv_null, tv_diagnose_time, textView3, info1, info2, yuyin, tv_diagnose_status;
            ImageView img, img_loading, img_head;
            LinearLayout diagnose_container, begin_container;
            RecyclerView recyclerView;

            public Holder(View itemView) {
                super(itemView);
                tv_time = itemView.findViewById(R.id.tv_time);
                tv_content = itemView.findViewById(R.id.tv_content);
                btn_confirm = itemView.findViewById(R.id.btn_confirm);
                tv_diagnose = itemView.findViewById(R.id.tv_diagnose);
                diagnose_container = itemView.findViewById(R.id.diagnose_container);
                recyclerView = itemView.findViewById(R.id.recyclerView);
                img = itemView.findViewById(R.id.img);
                img_loading = itemView.findViewById(R.id.img_loading);
                tv_null = itemView.findViewById(R.id.tv_null);
                tv_diagnose_time = itemView.findViewById(R.id.tv_diagnose_time);
                img_head = itemView.findViewById(R.id.img_head);
                begin_container = itemView.findViewById(R.id.begin_container);
                textView3 = itemView.findViewById(R.id.textView3);
                info1 = itemView.findViewById(R.id.info1);
                info2 = itemView.findViewById(R.id.info2);
                yuyin = itemView.findViewById(R.id.yuyin);
                tv_diagnose_status = itemView.findViewById(R.id.tv_diagnose_status);
            }
        }
    }

    private void resetSpeakingPosition() {
        for (int i = 0; i < messageList.size(); i++) {
            messageList.get(i).isSpeaking = false;
        }
        chatAdapter.notifyItemRangeChanged(0, messageList.size());
    }


    /**
     * 获取minio服务器域名
     *
     * @time 2020/12/2 10:21
     */
    private void getPresignedUrl(String imgPathSel) {

        dialog = ProgressDialog.show(this, "提示", "正在上传中…", true, false, null);

        // bucket:   1-病历 2-评论(反馈) 3-头像 4-轮播图 9-聊天图片 ',
        RestProxy.getInstance().getPresignedUrl("9", new Observer<String>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(String baseStringResponse) {
                try {
                    String data = baseStringResponse;
                    if (data.contains("?")) {
                        String substring = data.substring(0, data.indexOf("?"));
                        resourceId = substring.substring(substring.lastIndexOf("/") + 1);
                        Log.e("presignedUrl -----", resourceId);
                        uploadFileMinio(imgPathSel,baseStringResponse);
                    }

                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }

            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(NurseConsultChatActivity.this, e);
            }

            @Override
            public void onComplete() {
            }
        });
    }

    /**
     * 上传图片到minio服务器
     * <p>
     * * @time 2020/12/3 15:36
     */
    private void uploadFileMinio(String imgPath,String url) {
        new Thread(() -> {
            try {
                Log.e("TAG-路径-----", imgPath);
                File file = new File(imgPath);
                FileInputStream fileInputStream = new FileInputStream(file);
                int available = fileInputStream.available(); //返回与之关联的文件的字节数
                Log.e("字节数---", available + "");
                OkHttpClient httpClient = new OkHttpClient();
                MediaType mediaType = MediaType.parse("image/png");//设置类型
                RequestBody requestBody = RequestBody.create(mediaType, file);//把文件与类型放入请求体
                Request request = new Request.Builder()
                        .url(url)
                        .put(requestBody)
                        .build(); //创建OkHttpClient对象
                Call call = httpClient.newCall(request);
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        Log.e("TAG-失败：", e.toString() + "");
                        dialog.dismiss();
                    }

                    @Override
                    public void onResponse(Call call, Response response) {
                        String string = response.body().toString();
                        Log.e("minio成功---", string + "");
                        uploadFileTb(imgPath, available + "");
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
    }

    /**
     * 上传照片到服务器数据库
     *
     * @time 2020/12/2 9:55
     */
    private void uploadFileTb(String imgPathSel, String available) {
        // bucket:   1-病历 2-评论(反馈) 3-头像 4-轮播图 9-聊天图片 ',
        // type:   15-病历 2-评论(反馈) 30-头像 92-聊天图片 ',
        RestProxy.getInstance().uploadFileTb("9", "92", resourceId, BaseApplication.currentUserId, available, "1", new Observer<PicUploadResponse>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(PicUploadResponse picUploadResponse) {
                try {
                    runOnUiThread(() -> {
                        dialog.dismiss();
                        ChatResponse.Message message = new ChatResponse().new Message();
                        @SuppressLint("SimpleDateFormat") SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                        message.messageType = 1;
                        message.fromType = 0;
                        message.content = picUploadResponse.ShareThumbnailUrl == null ? picUploadResponse.shareThumbnailUrl : "";
                        message.src = picUploadResponse.shareUrl;
                        message.sendTime = df.format(new Date());
                        messageList.add(0, message);
                        chatAdapter.notifyItemInserted(0);
//                        chat_recyclerView.scrollToPosition( 0 );
                        nestedScrollView.fullScroll(ScrollView.FOCUS_DOWN);//滚动到底部
                        WebSocket webSocket = new WebSocket.Builder().content(picUploadResponse.ShareThumbnailUrl == null ? picUploadResponse.shareThumbnailUrl : "").docId(doctorId).diagnoseId(diagnoseId).from(BaseApplication.currentUserId).to(doctorUserId).picType("jpeg").src(picUploadResponse.shareUrl).msgType(1).eventFlag(1).clientId(TimeUtil.getClientId()).build();
                        EventBus.getDefault().postSticky(webSocket);
                    });

                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                }

            }

            @Override
            public void onError(Throwable e) {

                ToastUtil.onError(NurseConsultChatActivity.this, e);
            }

            @Override
            public void onComplete() {
//                dialog.dismiss();
            }
        });
    }

    @SuppressLint("CheckResult")
    private void checkVoicePermission() {
        ApplyPermissionDialog applyPermissionDialog = ApplyPermissionDialog.newInstance("4", true);
        applyPermissionDialog.show(getSupportFragmentManager(), "applyPermissionDialog");
        applyPermissionDialog.setmListener(new ApplyPermissionDialog.OnItemClickListener() {

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onConfirm() {
                RxPermissions permissions = new RxPermissions(NurseConsultChatActivity.this);
                permissions.request(Manifest.permission.RECORD_AUDIO, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .subscribe(granted -> {
                            if (granted) {
                                if (btnYuyin.getVisibility() == View.GONE) {
                                    btnYuyin.setVisibility(View.VISIBLE);
                                    edt_context.setVisibility(View.GONE);
                                    SoftKeyboardUtil.hideSoftKeyboard(mContext);
                                } else {
                                    btnYuyin.setVisibility(View.GONE);
                                    edt_context.setVisibility(View.VISIBLE);
                                }
                            } else {
                                ToastUtil.showToast(mContext, "请同意语音和存储权限，否则功能无法使用");
                                startNotificationSetting(mContext);
                            }
                        });
            }

            @Override
            public void onCancel() {

            }
        });


    }

    @SuppressLint("CheckResult")
    private void getPermission() {
        ApplyPermissionDialog applyPermissionDialog = ApplyPermissionDialog.newInstance("3", true);
        applyPermissionDialog.show(getSupportFragmentManager(), "applyPermissionDialog");
        applyPermissionDialog.setmListener(new ApplyPermissionDialog.OnItemClickListener() {

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onConfirm() {
                RxPermissions permissions = new RxPermissions(NurseConsultChatActivity.this);
                permissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                        .subscribe(granted -> {
                            if (granted) {
                                //已经打开权限
                                showSelectHeadPicDialog();
                            } else {
                                ToastUtil.showToast(mContext, "请同意相册和存储权限，否则功能无法使用");
                                startNotificationSetting(mContext);
                            }
                        });
            }

            @Override
            public void onCancel() {

            }
        });
    }

    private void showSelectHeadPicDialog() {
        if (mSelectPicModeDialog == null) {
            // 初始化点击头像弹出的对话框
            mSelectPicModeDialog = SelectPicModeDialog.newInstance();
            mSelectPicModeDialog.setOnItemClickListener(new SelectPicModeDialog.OnItemClickListener() {
                @Override
                public void takePhotoClick() {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File oriPhotoFile = null;
                    try {
                        oriPhotoFile = createOriImageFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
                        imgUriOri = Uri.fromFile(oriPhotoFile);
                    } else {
                        imgUriOri = FileProvider.getUriForFile(NurseConsultChatActivity.this, UIConstants.FILE_PROVIDER_URI, oriPhotoFile);
                    }
//                    phoneCamearUri = FileProvider.getUriForFile(PersonInfoActivity.this,"com.joyoung.robot.phone.provider",file);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUriOri);
                    intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                    startActivityForResult(intent, AddRegistrationActivity.REQUEST_OPEN_CAMERA);
                }

                @Override
                public void pickFromAlbumClick() {
                    Intent intent = new Intent(
                            Intent.ACTION_PICK,
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(intent, AddRegistrationActivity.REQUEST_GALLERY);
                }
            });
        }
        mSelectPicModeDialog.show(getSupportFragmentManager(), "SelectPicModeDialog");
    }

    /**
     * 创建原图像保存的文件
     *
     * @return
     * @throws IOException
     */
    protected File createOriImageFile() throws IOException {
        String imgNameOri = "HomePic_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File pictureDirOri = new File(getExternalFilesDir(Environment.DIRECTORY_PICTURES).getAbsolutePath() + "/OriPicture");
        if (!pictureDirOri.exists()) {
            pictureDirOri.mkdirs();
        }
        File image = File.createTempFile(
                imgNameOri,         /* prefix */
                ".jpg",             /* suffix */
                pictureDirOri       /* directory */
        );
        imgPathOri = image.getAbsolutePath();
        return image;
    }

    @Override
    public void finishNurseConsultChatActivity() {
        finish();
    }
}
